package com.qf.blog.web.controller;

import com.qf.blog.core.dto.EmailDto;
import com.qf.blog.core.exception.JsonException;
import com.qf.blog.core.utils.EmailUtils;
import com.qf.blog.core.utils.R;
import com.qf.blog.web.entity.UserEntity;
import com.qf.blog.web.service.IUserService;
import com.qf.blog.web.service.impl.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/userController")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private LikeService likeService;

    @PostMapping("/register")
    @ResponseBody
    public R register(@RequestBody UserEntity userEntity) throws Exception {

        // 1.判断当前邮箱或者用户名是否已经被注册了(去数据库根据用户名或者邮箱查询一下)

        // 2.调用业务层的注册方法
        userService.register(userEntity);
        String activationCode = userEntity.getActivationCode();

        // 3.给用户的邮箱发送激活账号的连接
        EmailDto emailDto = new EmailDto();
        emailDto.setTilte("Blog新用户注册账号激活");
        emailDto.setToUser(userEntity.getEmail());
        emailDto.setContent("<a href = 'http://2207.com:8080/UserServlet/activation?code=" + activationCode + "'>点击这里激活</a>");

        // 启动一个线程去发送邮件，这个子线程会执行3.3s
        new Thread(() -> {
            // 假设发送邮件代码需要3.3s
            try {
                // 邮件发送完成后需要记录邮件发送的状态(成功或失败)
                // 如果是失败了要把这个邮件持久化了(保存到数据库)，然后启动一个定时任务去轮训的发邮件
                EmailUtils.sendEmailInfoUser(emailDto);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

        // 4.提示用户
        return R.ok();
    }

    // 激活哪个账号？
    // 在一个接口中可能返回json，也有可能是视图
    @GetMapping("/activation")
    public String activation(@RequestParam("code") String activationCode) throws Exception {
        // 1.获取激活码
        System.out.println("激活码:" + activationCode);
        // 2.验证
        UserEntity userEntity = userService.byActivationCode(activationCode);
        if (userEntity == null) {
            System.out.println("激活码有误");
            // 抛出一个异常--》全局异常管理器--》把异常异常处理后以JSON格式响应
            throw new JsonException(101, "激活码有误");
        } else {
            userEntity.setStatus(2);
            userService.updateById(userEntity);
            return "redirect:/view/site/login.html"; // 返回的视图
        }
    }

    @PostMapping("/login")
    @ResponseBody
    public R login(@RequestBody UserEntity userEntity, HttpSession session) throws Exception {

        userEntity = userService.login(userEntity.getUsername(), userEntity.getPassword());
        // 判断认证成功
        if (userEntity == null) {
            return R.error("用户名获密码错误");
        }

        // 登录成功
        userEntity.setPassword(null); // 把密码设置为null，然哎放到session中
        session.setAttribute("loginUser", userEntity);
        return R.ok();
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) throws Exception {
        session.invalidate(); //  注销 sid失效
        return "redirect:/view/site/login.html";
    }

    @PostMapping("/updateHeaderPng")
    @ResponseBody
    public R updateHeaderPng(@RequestBody Map<String, Object> map, HttpSession session) {

        // 1.获取登录用户
        UserEntity userEntity = (UserEntity) session.getAttribute("loginUser");

        // 2.判断是否登录
        if (userEntity == null) {
            throw new JsonException(101, "请先登录");
        }

        // 3.更新用户的头像地址
        String pngPath = map.get("pngPath").toString();
        userService.updateHeaderUrl(userEntity.getId(), pngPath);
        return R.ok();
    }

    @GetMapping("/info/{id}")
    public String info(@PathVariable Integer id, ModelMap modelMap) {
        UserEntity userEntity = userService.getById(id);
        userEntity.setPassword(null);

        // 查询用户的点赞数量
        Long likeCount = likeService.getUserLikeCount(userEntity.getId());

        modelMap.put("userManager", userEntity);
        modelMap.put("hasFollowed", false); // 没有关注
        modelMap.put("followerCount", 0); // 它关注了多少人
        modelMap.put("fansCount", 0); // 它有多少粉丝
        modelMap.put("userLikeCount", likeCount); // 它有的多少个赞(帖子，评论)
        return "view/site/profile";
    }
}
